#include "UpdateSpeedCounter.hpp"


UpdateSpeedCounter::UpdateSpeedCounter()
:_currentSize(0),
_lastCurrentSize(0),
_speed(0),
_doTimer(false),
_timer(1.0f)
{
    
}

void UpdateSpeedCounter::startSpeedCounter()
{
    if (!_doTimer)
    {
        _doTimer = true;
        _speedCountList.clear();
        _speed = 0;
        _currentSize = 0;
        _lastCurrentSize = 0;
    }
}

void UpdateSpeedCounter::stopSpeedCounter()
{
    if (_doTimer)
    {
        _doTimer = false;
        _speedCountList.clear();
        _speed = 0;
    }
}

void UpdateSpeedCounter::setSize(size_t size)
{
    _currentSize = size;
}

void UpdateSpeedCounter::speedCounter(float dt)
{
    if (!_doTimer)
        return;
    _timer -= dt;
    if (_timer <= 0)
    {
        _timer = 1.0f;
        size_t thisSecondSize = _currentSize - _lastCurrentSize;
        _lastCurrentSize = _currentSize;
        if (_speedCountList.size() >= 5)
        {
            _speedCountList.pop_front();
            _speedCountList.push_back(thisSecondSize);
        }
        else
        {
            _speedCountList.push_back(thisSecondSize);
        }
        _speed = thisSecondSize;
    }
}

size_t UpdateSpeedCounter::getSpeed()
{
    size_t sum = 1;
    size_t total = 0;
    size_t totalsize = 0;
    for (size_t s : _speedCountList)
    {
        totalsize += s * sum * sum;
        total += sum * sum;
        sum++;
    }
    size_t _speed1 = (size_t)(totalsize / (total > 0 ? total : 1));
    return _speed1;
}

size_t UpdateSpeedCounter::getCurrentSpeed()
{
    return _speed;
}


